﻿using JYH.Business;
using JYH.Framework;
using JYH.Model.API;
using JYH.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Security;
using Microsoft.AspNetCore.Cors;
using JYH.Data;
using System.Text;
using JYH.Web.MES.Models;
using JYH.DataAccess;
using Newtonsoft.Json.Serialization;
using System.Reflection;
using FastReport.Data;

namespace JYH.Web.MES.Controllers
{
    [EnableCors("AllowSpecificOrigin")]
    public class BASController : ApiController
    {
        /// <summary>
        /// 保存仓库对象
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage SaveBasWarehouseInfo([FromBody] dynamic info)
        {
            Sql sql = new Sql();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, Msg);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                BasWarehouseInfoBLL bll = new BasWarehouseInfoBLL();
                BasWarehouseInfo obj = new BasWarehouseInfo();
                sql = new Sql();
                sql.Append(bll.SqlSelect);
                sql.Append("Where BasWarehouseInfo.WarehouseNO='" + info.WarehouseNO + "'");
                obj = bll.myDataBase.SingleOrDefault<BasWarehouseInfo>(sql);
                if (obj == null)
                {
                    obj = new BasWarehouseInfo();
                    obj.WarehouseID = Guid.NewGuid().ToString();
                    obj.WarehouseNO = info.WarehouseNO;
                    obj.WarehouseName = info.WarehouseName;
                    obj.CreateUser = SysUserInfoBLL.GetCookieUser().UserName;
                    bll.myDataBase.Insert(obj);
                }
                else
                {
                    Msg = "Error Repeat !";
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError, Msg);
                    return response;
                }
                response = Request.CreateResponse(HttpStatusCode.OK, Msg);
            }
            catch (Exception ex)
            {
                Msg = ex.ToString();
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, Msg);
            }

            return response;
        }

        /// <summary>
        /// 删除仓库信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteBasWarehouseInfo([FromBody] dynamic info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功!";
            var response = Request.CreateResponse(HttpStatusCode.OK, Msg);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                BasWarehouseInfoBLL bll = new BasWarehouseInfoBLL();
                BasWarehouseInfo obj = new BasWarehouseInfo();
                sb.Append("Update BasWarehouseInfo Set RState='99' Where  BasWarehouseInfo.WarehouseID='" + info.WarehouseID + "'");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
                response = Request.CreateResponse(HttpStatusCode.OK, Msg);
            }
            catch (Exception ex)
            {
                Msg = ex.ToString();
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, Msg);
            }
            return response;
        }

        /// <summary>
        /// 检索仓库
        /// </summary>
        /// <param name="info">产品物料信息对象</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult QueryBasWarehouseInfo(int rows, int page, string WarehouseNO, string WarehouseName, string order, string sort)
        {
            Sql sql = new Sql();
            List<BasWarehouseInfo> list = new List<BasWarehouseInfo>();
            var lists = "";
            string Msg = string.Empty;
            long total = 0;
            try
            {
                BasWarehouseInfoBLL bll = new BasWarehouseInfoBLL();

                sql = new Sql();
                if (!string.IsNullOrEmpty(WarehouseNO))
                {
                    sql.Append("Where BasWarehouseInfo.WarehouseNO Like '%" + WarehouseNO + "%'");
                }
                if (!string.IsNullOrEmpty(WarehouseName))
                {
                    sql.Append("Where BasWarehouseInfo.WarehouseName Like '%" + WarehouseName + "%'");
                }
                sql.Append("Where BasWarehouseInfo.RState <>'99'");
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" BasWarehouseInfo." + sort + "  " + order);
                }
                else
                {
                    sql.OrderBy("BasWarehouseInfo.CreateTime ");
                }
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);
                var json = ConvertJson<BasWarehouseInfo>.ListToJson(list);
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
            }
            return Ok(lists);
        }

        /// <summary>
        /// 保存储位对象
        /// </summary>
        /// <param name="info">Json格式info</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage SaveBasStorageInfo([FromBody] dynamic info)
        {
            Sql sql = new Sql();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, Msg);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                BasStorageInfoBLL bll = new BasStorageInfoBLL();
                BasStorageInfo obj = new BasStorageInfo();
                sql = new Sql();
                sql.Append(bll.SqlSelect);
                sql.Append($"Where BasStorageInfo.StorageNO='{info.StorageNO}' And BasWarehouseInfo.WarehouseID='{info.WarehouseID}'");
                obj = bll.myDataBase.SingleOrDefault<BasStorageInfo>(sql);
                if (obj == null)
                {
                    obj = new BasStorageInfo();
                    obj.StorageID = Guid.NewGuid().ToString();
                    obj.WarehouseID = info.WarehouseID;
                    obj.StorageNO = info.StorageNO;
                    obj.CreateUser = SysUserInfoBLL.GetCookieUser().UserName;
                    bll.myDataBase.Insert(obj);
                }
                else
                {
                    Msg = "请勿重复添加库位!";
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError, Msg);
                    return response;
                }
                response = Request.CreateResponse(HttpStatusCode.OK, Msg);
            }
            catch (Exception ex)
            {
                Msg = ex.ToString();
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, Msg);
            }

            return response;
        }

        /// <summary>
        /// 检索库位
        /// </summary>
        /// <param name="info">产品物料信息对象</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult QueryBasStorageInfo(int rows, int page, string WarehouseID, string WarehouseName, string StorageNO, string sort, string order)
        {
            Sql sql = new Sql();
            List<BasStorageInfo> list = new List<BasStorageInfo>();
            var lists = "";
            string Msg = string.Empty;
            long total = 0;
            try
            {
                BasStorageInfoBLL bll = new BasStorageInfoBLL();

                sql = new Sql();
                if (!string.IsNullOrEmpty(WarehouseID))
                {
                    sql.Append("Where BasWarehouseInfo.WarehouseID Like '%" + WarehouseID + "%'");
                }
                if (!string.IsNullOrEmpty(WarehouseName))
                {
                    sql.Append("Where BasWarehouseInfo.WarehouseName Like '%" + WarehouseName + "%'");
                }
                if (!string.IsNullOrEmpty(StorageNO))
                {
                    sql.Append("Where BasStorageInfo.StorageNO Like '%" + StorageNO + "%'");
                }
                sql.Append("Where BasStorageInfo.RState <>'99'");
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" BasStorageInfo." + sort + "  " + order);
                }
                else
                {
                    sql.OrderBy("BasStorageInfo.CreateTime ");
                }
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);
                var json = ConvertJson<BasStorageInfo>.ListToJson(list);
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
            }
            return Ok(lists);
        }

        /// <summary>
        /// 删除库位信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteBasStorageInfo([FromBody] dynamic info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功!";
            var response = Request.CreateResponse(HttpStatusCode.OK, Msg);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                BasStorageInfoBLL bll = new BasStorageInfoBLL();
                BasStorageInfo obj = new BasStorageInfo();
                sb.Append("Update BasStorageInfo Set RState='99' Where  BasStorageInfo.StorageID='" + info.StorageID + "'");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
                response = Request.CreateResponse(HttpStatusCode.OK, Msg);
            }
            catch (Exception ex)
            {
                Msg = ex.ToString();
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, Msg);
            }
            return response;
        }

        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetWarehouseInfo()
        {
            ResponseJson<BasWarehouseInfo> json = new ResponseJson<BasWarehouseInfo>();
            json.Items = new List<BasWarehouseInfo>();
            string Msg = string.Empty;
            try
            {
                BasWarehouseInfoBLL bLL = new BasWarehouseInfoBLL();
                json.Items = bLL.NotPagedQuery(new Sql().Append("Where 1=1"), out Msg, " BasWarehouseInfo.WarehouseNO");
                if (!json.Items.Any())
                {
                    json.Code = 500;
                    return Content(HttpStatusCode.InternalServerError, "暂无数据");
                }
                return Ok(json.Items);
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json.Message);
            }
        }

        /// <summary>
        /// 物料信息保存
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage SaveMaterial([FromBody] BasMaterialInfo info)
        {
            ResponseJson<BasMaterialInfo> message = new ResponseJson<BasMaterialInfo>()
            {
                Items = new List<BasMaterialInfo>(),
                Code = 200,
                Message = "保存成功"
            };

            if (info == null || string.IsNullOrEmpty(info.MaterialNO))
            {
                message.Code = 400;
                message.Message = "物料编号不能为空";
                return Request.CreateResponse(HttpStatusCode.OK, message);
            }

            Sql sql = new Sql();
            string Msg = string.Empty;

            try
            {
                BasMaterialInfoBLL bll = new BasMaterialInfoBLL();
                sql.Append(bll.SqlSelect);
                sql.Append($" WHERE MaterialNO ='{info.MaterialNO}'");
                BasMaterialInfo obj = bll.myDataBase.SingleOrDefault<BasMaterialInfo>(sql);

                decimal qty = 0;

                if (obj != null)
                {
                    // 更新操作
                    obj.MaterialName = info.MaterialName;
                    obj.MaterialDesc = info.MaterialDesc;
                    obj.Humidity = info.Humidity;
                    qty = 0;
                    if (info.StockQty != null && decimal.TryParse(info.StockQty.ToString(), out qty))
                    {
                        obj.StockQty = qty;
                    }

                    qty = 0;
                    if (info.YokePlate != null && decimal.TryParse(info.YokePlate.ToString(), out qty))
                    {
                        obj.YokePlate = (int)qty;
                    }

                    qty = 0;
                    if (info.WarrantyDay != null && decimal.TryParse(info.WarrantyDay.ToString(), out qty))
                    {
                        obj.WarrantyDay = (int)qty;
                    }

                    qty = 0;
                    if (info.Exceeding != null && decimal.TryParse(info.Exceeding.ToString(), out qty))
                    {
                        obj.Exceeding = qty;
                    }

                    obj.UpdateUser = info.UpdateUser;

                    if (obj.RState == "9")
                    {
                        obj.RState = "1";
                    }

                    bll.myDataBase.Save(obj);
                }
                else
                {
                    // 插入操作
                    obj = new BasMaterialInfo();

                    obj.MaterialID = Guid.NewGuid().ToString(); // 建议替换为业务ID规则
                    obj.MaterialNO = info.MaterialNO;
                    obj.CreateUser = info.CreateUser;
                    obj.MaterialName = info.MaterialName;
                    obj.MaterialDesc = info.MaterialDesc;
                    obj.Humidity = info.Humidity;
                    qty = 0;
                    if (info.StockQty != null && decimal.TryParse(info.StockQty.ToString(), out qty))
                    {
                        obj.StockQty = qty;
                    }

                    qty = 0;
                    if (info.YokePlate != null && decimal.TryParse(info.YokePlate.ToString(), out qty))
                    {
                        obj.YokePlate = (int)qty;
                    }

                    qty = 0;
                    if (info.WarrantyDay != null && decimal.TryParse(info.WarrantyDay.ToString(), out qty))
                    {
                        obj.WarrantyDay = (int)qty;
                    }

                    qty = 0;
                    if (info.Exceeding != null && decimal.TryParse(info.Exceeding.ToString(), out qty))
                    {
                        obj.Exceeding = qty;
                    }

                    bll.myDataBase.Insert(obj);
                }

                message.Items.Add(obj);
            }
            catch
            {
                message.Code = 500;
                message.Message = "保存失败，请联系管理员";
                return Request.CreateResponse(HttpStatusCode.InternalServerError, message);
            }

            return Request.CreateResponse(HttpStatusCode.OK, message);
        }

        /// <summary>
        /// 保存供应商信息
        /// </summary>
        /// <param name="info">产品物料信息对象</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage SavePartner([FromBody] BasPartnerInfo info)
        {
            ResponseJson<BasPartnerInfo> message = new ResponseJson<BasPartnerInfo>();
            message.Code = 200;
            message.Message = "操作成功";
            message.Items = new List<BasPartnerInfo>();
            Sql sql = new Sql();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, message);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                BasPartnerInfoBLL bll = new BasPartnerInfoBLL();
                BasPartnerInfo obj = new BasPartnerInfo();
                sql = new Sql();
                sql.Append(bll.SqlSelect);
                sql.Append("Where BasPartnerInfo.PartnerNO='" + info.PartnerNO + "'");
                obj = bll.myDataBase.SingleOrDefault<BasPartnerInfo>(sql);

                if (obj != null)
                {
                    obj.RType = info.RType;
                    obj.BankName = info.BankName;
                    obj.BankNO = info.BankNO;
                    obj.PartnerNO = info.PartnerNO;
                    obj.TaxNO = info.TaxNO;
                    obj.PartnerName = info.PartnerName;
                    obj.InvoiceAddr = info.InvoiceAddr;
                    obj.InvoiceTel = info.InvoiceTel;
                    obj.Contacts = info.Contacts;
                    obj.UpdateUser = SysUserInfoBLL.GetCookieUser().UserName;
                    obj.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    if (obj.RState == "99")
                    {
                        obj.RState = "00";
                    }
                    bll.myDataBase.Save(obj);
                }
                else
                {
                    obj = new BasPartnerInfo();
                    obj.PartnerID = Guid.NewGuid().ToString();
                    obj.RType = info.RType;
                    obj.RState = "00";
                    obj.BankName = info.BankName;
                    obj.BankNO = info.BankNO;
                    obj.PartnerNO = info.PartnerNO;
                    obj.TaxNO = info.TaxNO;
                    obj.PartnerName = info.PartnerName;
                    obj.InvoiceAddr = info.InvoiceAddr;
                    obj.InvoiceTel = info.InvoiceTel;
                    obj.Contacts = info.Contacts;
                    obj.CreateUser = SysUserInfoBLL.GetCookieUser().UserName;
                    obj.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    bll.myDataBase.Insert(obj);
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return response;
        }

        /// <summary>
        /// 合作伙伴查询(分页)
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult QueryPartner(int rows, int page, string PartnerNO, string PartnerName, string order, string sort)
        {
            Sql sql = new Sql();
            List<BasPartnerInfo> list = new List<BasPartnerInfo>();
            var lists = "";
            string Msg = string.Empty;
            long total = 0; try
            {
                BasPartnerInfoBLL bll = new BasPartnerInfoBLL();
                BasPartnerInfo obj = new BasPartnerInfo();
                sql = new Sql();
                if (!string.IsNullOrEmpty(PartnerName))
                {
                    sql.Append("Where BasPartnerInfo.PartnerName Like '%" + PartnerName + "%'");
                }
                if (!string.IsNullOrEmpty(PartnerNO))
                {
                    sql.Append("Where BasPartnerInfo.PartnerNO Like '%" + PartnerNO + "%'");
                }
                sql.Append("Where BasPartnerInfo.RState <>'99'");
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" BasPartnerInfo." + sort + "  " + order);
                }
                else
                {
                    sql.OrderBy("BasPartnerInfo.CreateTime ");
                }

                list = bll.PagedQuery(page, rows, sql, out total, out Msg);
                var json = ConvertJson<BasPartnerInfo>.ListToJson(list);
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
            }
            return Ok(lists);
        }

        /// <summary>
        /// 合作伙伴查询
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult QPartner([FromBody] dynamic info)
        {
            Sql sql = new Sql();
            List<BasPartnerInfo> list = new List<BasPartnerInfo>();
            string Msg = string.Empty;

            try
            {
                BasPartnerInfoBLL bll = new BasPartnerInfoBLL();
                BasPartnerInfo obj = new BasPartnerInfo();
                sql = new Sql();

                sql.Append("Where BasPartnerInfo.RState <>'99'");
                sql.OrderBy("BasPartnerInfo.CreateTime ");

                list = bll.NotPagedQuery(sql, out Msg);
                //var json = ConvertJson<BasPartnerInfo>.ListToJson(list);
            }
            catch
            {
            }
            return Ok(ConvertJson<BasPartnerInfo>.ListToJson(list));
        }

        /// <summary>
        /// 删除合作伙伴
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePartner([FromBody] List<BasPartnerInfo> info)
        {
            ResponseJson<BasPartnerInfo> message = new ResponseJson<BasPartnerInfo>();
            message.Code = 200;
            message.Message = "操作成功";
            message.Items = new List<BasPartnerInfo>();
            StringBuilder sb = new StringBuilder();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, message);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                BasPartnerInfoBLL bll = new BasPartnerInfoBLL();
                for (int i = 0; i < info.Count; i++)
                {
                    sb.Append("Update BasPartnerInfo Set RState='99' Where  BasPartnerInfo.PartnerID='" + info[i].PartnerID + "'");
                }
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return response;
        }

        /// <summary>
        /// 合作伙伴审核
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage ApprovePartner([FromBody] List<BasPartnerInfo> info)
        {
            ResponseJson<BasPartnerInfo> message = new ResponseJson<BasPartnerInfo>();
            message.Code = 200;
            message.Message = "操作成功";
            message.Items = new List<BasPartnerInfo>();
            StringBuilder sb = new StringBuilder();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, message);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                BasMaterialInfoBLL bll = new BasMaterialInfoBLL();
                for (int i = 0; i < info.Count; i++)
                {
                    sb.Append("Update BasPartnerInfo Set RState='11' Where  BasPartnerInfo.PartnerID='" + info[i].PartnerID + "'");
                }
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return response;
        }

        /// <summary>
        /// 合作伙伴反审
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdoPartner([FromBody] List<BasPartnerInfo> info)
        {
            //List<BasMaterialInfo> infos = JsonConvert.DeserializeObject<List<BasMaterialInfo>>(info);

            ResponseJson<BasPartnerInfo> message = new ResponseJson<BasPartnerInfo>();
            message.Code = 200;
            message.Message = "操作成功";
            message.Items = new List<BasPartnerInfo>();
            StringBuilder sb = new StringBuilder();
            string Msg = string.Empty;
            var response = Request.CreateResponse(HttpStatusCode.OK, message);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            try
            {
                BasMaterialInfoBLL bll = new BasMaterialInfoBLL();
                for (int i = 0; i < info.Count; i++)
                {
                    sb.Append("Update BasPartnerInfo Set RState='00' Where  BasPartnerInfo.PartnerID='" + info[i].PartnerID + "'");
                }
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return response;
        }

        /// <summary>
        /// 删除收料单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteWmsReciveOrderInfo([FromBody] List<BasMaterialInfo> info)
        {
            StringBuilder sb = new StringBuilder();
            string Msg = "操作成功!";
            try
            {
                BasMaterialInfoBLL bll = new BasMaterialInfoBLL();
                string Ids = "";
                foreach (var item in info)
                {
                    Ids += "'" + item.MaterialID + "',";
                }
                Ids = Ids.Substring(0, Ids.Length - 1);
                sb.Append("Update BasMaterialInfo Set RState='99' Where  BasMaterialInfo.MaterialID in (" + Ids + ")");
                if (sb.Length > 0)
                    bll.myDataBase.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(Msg);
        }

        /// <summary>
        /// 查询产品物料全信息
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="MaterialNO">物料编号，用于模糊查询</param>
        /// <param name="MaterialName">物料名称，用于模糊查询</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult QueryMaterial(int rows, int page, string MaterialNO, string MaterialName, string order, string sort)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<BasMaterialInfo> list = new List<BasMaterialInfo>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                BasMaterialInfoBLL bll = new BasMaterialInfoBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(MaterialName))
                {
                    sql.Append("Where BasMaterialInfo.MaterialName Like '%" + MaterialName + "%'");
                }

                // 如果物料编号不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%'");
                }

                // 过滤掉状态为 '99' 的记录（可能是已删除或无效状态）
                sql.Append("Where BasMaterialInfo.RState <>'99'");

                // 如果有指定排序字段和顺序，则按指定方式排序
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" BasMaterialInfo." + sort + "  " + order);
                }
                else
                {
                    // 默认按创建时间升序排序
                    sql.OrderBy("BasMaterialInfo.CreateTime desc");
                }

                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<BasMaterialInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 获取产品物料全信息
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="MaterialNO">物料编号，用于模糊查询</param>
        /// <param name="MaterialName">物料名称，用于模糊查询</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult QueryGetMaterial()
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<BasMaterialInfo> list = new List<BasMaterialInfo>();

            // 用于存储操作消息
            string Msg = string.Empty;
            try
            {
                // 创建业务逻辑层实例
                BasMaterialInfoBLL bll = new BasMaterialInfoBLL();
                // 执行分页查询
                list = bll.NotPagedQuery(sql, out Msg, "BasMaterialInfo.CreateTime desc");
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(list);
        }

        /// <summary>
        /// 查询条码全信息
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="BarcodeNO">物料编号，用于模糊查询</param>
        /// <param name="MaterialNO">物料名称，用于模糊查询</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult QueryBarcodeInfo(int rows, int page, string BarcodeNO, string MaterialNO, string ReciveOrderNO, string order, string sort)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<BasBarcodeInfo> list = new List<BasBarcodeInfo>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                BasBarcodeInfoBLL bll = new BasBarcodeInfoBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(BarcodeNO))
                {
                    sql.Append("Where BasBarcodeInfo.BarcodeNO Like '%" + BarcodeNO + "%'");
                }

                // 如果物料编号不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%'");
                }
                if (!string.IsNullOrEmpty(ReciveOrderNO))
                {
                    sql.Append("Where WmsReciveOrderInfo.ReciveOrderNO Like '%" + ReciveOrderNO + "%'");
                }
                // 过滤掉状态为 '99' 的记录（可能是已删除或无效状态）
                sql.Append("Where BasBarcodeInfo.RState <>'99'");

                // 如果有指定排序字段和顺序，则按指定方式排序
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" BasBarcodeInfo." + sort + "  " + order);
                }
                else
                {
                    // 默认按创建时间升序排序
                    sql.OrderBy("BasBarcodeInfo.CreateTime  desc");
                }

                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<BasBarcodeInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        /// 查询打印条码
        /// </summary>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="page">当前请求的页码</param>
        /// <param name="BarcodeNO">物料编号，用于模糊查询</param>
        /// <param name="MaterialNO">物料名称，用于模糊查询</param>
        /// <param name="order">排序方式（ASC 或 DESC）</param>
        /// <param name="sort">排序字段名称</param>
        /// <returns>返回分页查询结果，包含总记录数和当前页数据</returns>
        [HttpGet]
        public IHttpActionResult Query_PrintBarcodeInfo(int rows, int page, string BarcodeNO, string MaterialNO, string PartnerNO, string SourceOrderNO, string MaterialName, int printQty, string order, string sort)
        {
            // 初始化 SQL 构造器
            Sql sql = new Sql();
            // 用于存储查询结果的列表
            List<BasBarcodeInfo> list = new List<BasBarcodeInfo>();
            // 存储最终返回的 JSON 字符串
            var lists = "";
            // 用于存储操作消息
            string Msg = string.Empty;
            // 查询结果的总记录数
            long total = 0;

            try
            {
                // 创建业务逻辑层实例
                BasBarcodeInfoBLL bll = new BasBarcodeInfoBLL();

                // 如果物料名称不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(BarcodeNO))
                {
                    sql.Append("Where BasBarcodeInfo.BarcodeNO Like '%" + BarcodeNO + "%'");
                }

                // 如果物料编号不为空，则添加模糊查询条件
                if (!string.IsNullOrEmpty(MaterialNO))
                {
                    sql.Append("Where BasMaterialInfo.MaterialNO Like '%" + MaterialNO + "%'");
                }
                if (!string.IsNullOrEmpty(PartnerNO))
                {
                    sql.Append("Where (BasPartnerInfo.PartnerNO Like '%" + PartnerNO + "%' or  BasPartnerInfo.PartnerName Like '%" + PartnerNO + "%' )");
                }
                if (!string.IsNullOrEmpty(SourceOrderNO))
                {
                    sql.Append("Where WmsReciveOrderInfo.ReciveOrderNO Like '%" + SourceOrderNO + "%'");
                }
                if (!string.IsNullOrEmpty(MaterialName))
                {
                    sql.Append("Where BasMaterialInfo.MaterialName Like '%" + MaterialName + "%'");
                }
                if (printQty == 0)
                {
                    sql.Append($"Where BasBarcodeInfo.Prints= 0");
                }
                // 过滤掉状态为 '99' 的记录（可能是已删除或无效状态）
                sql.Append("Where BasBarcodeInfo.RState <>'99' ");

                // 如果有指定排序字段和顺序，则按指定方式排序
                if (!string.IsNullOrEmpty(sort) && !string.IsNullOrEmpty(order))
                {
                    sql.OrderBy(" BasBarcodeInfo." + sort + "  " + order);
                }
                else
                {
                    // 默认按创建时间升序排序
                    sql.OrderBy("BasBarcodeInfo.CreateTime desc");
                }

                // 执行分页查询
                list = bll.PagedQuery(page, rows, sql, out total, out Msg);

                // 将查询结果转换为 JSON 格式
                var json = ConvertJson<BasBarcodeInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + total + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }

        /// <summary>
        ///  物料条码生成(批量)
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SaveBarcodeInfo([FromBody] List<BasBarcodeInfo> info)
        {
            ResponseJson<BasBarcodeInfo> message = new ResponseJson<BasBarcodeInfo>()
            {
                Items = new List<BasBarcodeInfo>()
            };
            BasBarcodeInfoBLL basBarcodeInfo = new BasBarcodeInfoBLL();
            try
            {
                info[0].CreateUser = SysUserInfoBLL.GetCookieUser().UserNO;
                if (!basBarcodeInfo.SaveBarcodeInfo(info, ref message))
                {
                    message.Code = 500;
                }
            }
            catch (Exception ex)
            {
                return Content(HttpStatusCode.InternalServerError, ex.ToString());
            }
            return Ok(message);
        }

        /// <summary>
        /// 数据同步
        /// </summary>
        /// <param name="Date">同步日期</param>
        /// <param name="NO">数据编号</param>
        /// <param name="Msg">反馈信息</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SynchronousData([FromBody] SyncDataModel info)
        {
            ResponseJson<SyncDataModel> message = new ResponseJson<SyncDataModel>()
            {
                Items = new List<SyncDataModel>()
            };
            try
            {
                string Msg = string.Empty;
                string Date = info.Date;
                string NO = info.NO;
                string MethodName = info.MethodName;
                object[] args = { Date, NO, Msg };
                bool res = SyncData.SynchronousData("", MethodName, args, out Msg);
                if (!res)
                {
                    message.Code = 500;
                    message.Message = Msg;
                }
                else
                {
                    message.Code = 200;
                }
            }
            catch (Exception ex)
            {
                message.Code = 500;
                message.Message = ex.Message;
            }
            return Ok(message);
        }

        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <param name="Info"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetLampControl()
        {
            ResponseJson<BasLampControl> json = new ResponseJson<BasLampControl>();
            json.Items = new List<BasLampControl>();
            string Msg = string.Empty;
            try
            {
                Database db = DB.D();
                Sql sql = new Sql();
                sql.Append("Select BasLampControl.* From BasLampControl");
                sql.Where("BasLampControl.DoTime<='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'");
                sql.Where("BasLampControl.RState ='0'");
                sql.OrderBy("BasLampControl.DoTime");
                json.Items = db.Fetch<BasLampControl>(sql);
                if (!json.Items.Any())
                {
                    json.Code = 500;
                }
                else
                {
                    List<string> NOs = new List<string>();
                    for (int i = 0; i < json.Items.Count; i++)
                    {
                        NOs.Add(json.Items[i].LampNO);
                    }
                    NetWorkLayerHelper.InitComNetClient();
                    NetWorkLayerHelper.MutiShelfLEDBatchControl(0, NOs, false, false);
                    db.Execute(@"Update BasLampControl Set RState ='1' Where BasLampControl.DoTime<='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'");
                }
                var settings = new JsonSerializerSettings
                {
                    ContractResolver = new IgnoreBackingFieldsResolver()
                };
                return Ok(JsonConvert.SerializeObject(json, settings));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                json.Code = 500;
                return Content(HttpStatusCode.InternalServerError, json);
            }
        }

        public class IgnoreBackingFieldsResolver : DefaultContractResolver
        {
            protected override List<MemberInfo> GetSerializableMembers(Type objectType)
            {
                var members = base.GetSerializableMembers(objectType);
                return members.Where(m => !m.Name.Contains(">k__BackingField")).ToList();
            }
        }

        /// <summary>
        /// 依据收料单号或收料明细项获取条码
        /// </summary>
        /// <param name="ReceiveOrderNO">收料单号</param>
        /// <param name="ReciveItemID">收料明细项ID,可以为空</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetBarcodeByReceiveOrder(string ReciveOrderNO, string ReciveItemID)
        {
            var lists = "";
            string Msg = string.Empty;
            BasBarcodeInfoBLL bll = new BasBarcodeInfoBLL();
            List<BasBarcodeInfo> list = new List<BasBarcodeInfo>();
            try
            {
                // 创建业务逻辑层实例

                list = bll.GetBarcodeByReceiveOrder(ReciveOrderNO, ReciveItemID, out Msg);
                var json = ConvertJson<BasBarcodeInfo>.ListToJson(list);

                // 构建返回的 JSON 字符串，包含总记录数和当前页的数据
                lists = "{\"total\":" + list.Count + ",\"rows\":" + json + "}";
            }
            catch
            {
                // 异常处理（当前未做具体处理，建议记录日志）
            }

            // 返回查询结果
            return Ok(lists);
        }
    }
}